﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ext.Net;
using System.Globalization;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;
using System.Web.Services;
using System.Web.Security;

namespace BitPortal.Handlers
{
    /// <summary>
    /// Trả về danh sách tài khoản người dùng bắt đầu bằng chữ cái nhập vào
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomerUserListRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            var start = 0;
            var limit = 10;
            string sort = null;
            string dir = null;
            string query = "";
            if (!string.IsNullOrEmpty(context.Request["query"]))
            {
                query = context.Request["query"];
            }
            if (!string.IsNullOrEmpty(context.Request["start"]))
            {
                start = context.Request["start"].ToInt32TryParse();
            }
            if (!string.IsNullOrEmpty(context.Request["limit"]))
            {
                limit = context.Request["limit"].ToInt32TryParse();
            }
            if (!string.IsNullOrEmpty(context.Request["sort"]))
            {
                sort = context.Request["sort"];
            }
            if (!string.IsNullOrEmpty(context.Request["dir"]))
            {
                query = context.Request["dir"];
            }
            var userlist = UserBLL.GetByRole("Customer");
            int count = userlist.Count;
            var users = userlist.Where(ent => (ent.UserName.StartsWith(query, StringComparison.OrdinalIgnoreCase) || ent.Email.StartsWith(query, StringComparison.OrdinalIgnoreCase)) && ent.UserName != "RootAdmin").Select(ent => new { UserName = ent.UserName, Email = ent.Email }).ToList();
            users = users.DataProcessing(null, sort: sort, dir: dir, start: start, limit: limit);
            context.Response.Write(string.Format("{{total:{1},'customeruser':{0}}}", JSON.Serialize(users), count));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}